<template>
  <div>
    <div class="main" v-for="(itemgroup, index) in menu" :key="index">
      <div class="submain" v-for="(itemkey, key) in itemgroup" :key="key">
        <template v-if="itemkey.title">
          <div class="menutitle">{{ itemkey.title }}</div>
          <van-grid :border="false">
            <van-grid-item v-for="item in itemkey.value" :key="item.stitle" :text="item.stitle" :icon="item.icon" @click="openList(item)" />
          </van-grid>
        </template>
        <template v-else><!-- 旧版适配 -->
          <div class="menutitle">{{ key }}</div>
          <van-grid>
            <van-grid-item v-for="item in itemkey" :key="item.stitle" :text="item.stitle" :icon="item.icon" @click="openList(item)" />
          </van-grid>
        </template>
      </div>
    </div>
    <van-tabbar v-model="buttomactive" safe-area-inset-bottom>
      <van-tabbar-item icon="home-o" @click="menuChange('homepage')">主页</van-tabbar-item>
      <van-tabbar-item icon="label-o" @click="menuChange('flowlist')" :badge="badgenum">审批</van-tabbar-item>
      <van-tabbar-item icon="qr" @click="menuChange('main')">功能</van-tabbar-item>
      <van-tabbar-item icon="chart-trending-o" @click="menuChange('report')">分析</van-tabbar-item>
      <van-tabbar-item icon="user-o" @click="menuChange('mine')">我的</van-tabbar-item>
    </van-tabbar>
    <van-popup v-model="usershow" position="bottom">
      <van-cell clickable @click="changePwd">
        <div style="text-align:center;">修改密码</div>
      </van-cell>
      <van-cell clickable @click="loginout">
        <div style="text-align:center;">退出</div>
      </van-cell>
    </van-popup>
  </div>
</template>

<script>
import Vue from 'vue'
import { Grid, GridItem, Toast, Popup, Tabbar, TabbarItem } from 'vant'
import qs from 'qs'
import * as dd from 'dingtalk-jsapi'
import wx from 'weixin-js-sdk'
import Utils from '@/utils/utils'
import YYEsnBridge from '@/assets/js/esn.min.js'

Vue.use(Grid).use(GridItem).use(Toast).use(Popup).use(Tabbar).use(TabbarItem)
export default {
  name: 'Main',
  data () {
    return {
      corpId: this.$route.params.corpId,
      menu: [],
      clickmenu: '',
      username: '',
      usershow: false,
      buttomactive: 2,
      badgenum: '',
      clttype: 'browser',
      logintype: 'nosass'
    }
  },
  activated () {
    document.querySelector('body').setAttribute('style', 'padding-bottom:8vh')
  },
  deactivated () {
    document.querySelector('body').removeAttribute('style')
  },
  created: function () {
    let data = {}
    this.axios({
      method: 'post',
      url: '/api/default.menu.do',
      data: qs.stringify(data)
    }).then(res => {
      //console.log(res)
      if (res.data.flag === '1') {
        Toast(res.data.des)
        if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
          this.loginout()
        }
      } else {
        this.menu = res.data.jsondata.menu
        this.username = res.data.jsondata.username
        if (res.data.jsondata.badgenum) {
          // 0不显示
        } else {
          this.badgenum = res.data.jsondata.badgenum
        }
        if (res.data.jsondata.watermark === '1') {
          // 显示水印
          Utils.$emit('fetchusername', this.username)
        }
      }
    }).catch(res => {
      this.reserror(res)
    })

    let ua = window.navigator.userAgent.toLowerCase()
    // alert(ua)
    //console.log('ua:' + ua)
    this.logintype = 'wechat'
    let tourl = window.location.href
    if (ua.toLowerCase().indexOf('iphone'.toLowerCase()) !== -1 || ua.toLowerCase().indexOf('ipad'.toLowerCase()) !== -1) {
      this.clttype = 'ios'
    } else if (ua.toLowerCase().indexOf('android'.toLowerCase()) !== -1) {
      this.clttype = 'android'
    }
    if (ua.indexOf('wxwork') !== -1) {
      this.logintype = 'wxwork'
    } else if (ua.indexOf('dingtalk') !== -1) {
      this.logintype = 'dingding'
    } else if (ua.indexOf('micromessenger') !== -1) {
      this.logintype = 'wechat'
    } else if (ua.indexOf('tenantid') !== -1) {
      // 友空间
      this.logintype = 'ykj'
    } else {
      this.logintype = 'nosass'
    }
    //console.log('main logintype', this.logintype, this.$route.state)
    this.$store.commit('setlogintype', this.logintype)
    //console.log('main logintype', this.logintype, this.$route.state)

    if (this.clttype === 'browser') {
      Toast('请在钉钉或微信端登录!')
      return
      // this.$router.go(-1)
    }
    if (this.logintype == 'nosass') {
      return
    }

    let url = '/api/default.getlocation.do'
    // alert("begin axios")
    // alert(this.idobject)
    this.axios({
      method: 'post',
      url: url,
      data: qs.stringify({
        url: tourl,
        type: this.logintype,
        clttype: this.clttype,
        corpid: this.corpId
      })
    }).then(res => {
      if (res.data.flag === '1' && res.data.des && res.data.des.indexOf('登录过期') >= 0) {
        Toast(res.data.des)
        this.loginout()
      } else {
        // alert("success axios" + JSON.stringify(res))
        let data = res.data

        const projectData = require('../project.json')
        if (projectData.project === 'chenxin/' || projectData.project === 'yongchen/' || projectData.project === 'xinsheng/') {
          return
        }

        if (this.logintype === 'wechat' || this.logintype === 'wxwork') {
          // alert('config wx')
          wx.config({
            beta: true,
            debug: false,
            appId: data.appId,
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            jsApiList: [
              'chooseImage',
              'previewImage',
              'uploadImage',
              'downloadImage',
              'previewFile',
              'getLocation'
            ]
          })
          wx.error(function (err) {
            // alert(JSON.stringify(err))
            //console.log('wx.error', err)
          })
        } else if (this.logintype === 'dingding') {
          //console.log('dingding data', data)
          // alert("config dd")
          dd.config({
            agentId: data.agentid,
            corpId: data.appId,
            timeStamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            type: 0,
            jsApiList: [
              'biz.util.uploadImage',
              'biz.util.chooseImage',
              'runtime.info',
              'biz.contact.choose',
              'device.notification.confirm',
              'device.notification.alert',
              'device.notification.prompt',
              'biz.ding.post',
              'biz.util.openLink',
              'device.geolocation.get'
            ]
          })
          dd.error(function (error) {
            // alert('dd error: ' + JSON.stringify(error))
            //console.log('dd.error', error)
          })
        } else if (this.logintype === 'ykj') {
          YYEsnBridge.do('config', {
            signature: data.signature,
            agentId: data.appId,
            timeStamp: data.timestamp,
            success: function () {
              // alert('success')
              //console.log('success')
            },
            fail: function (error) {
              alert('ykj error: ' + JSON.stringify(error))
            }

          })
        }
      }
    }).catch(function (error) {
      alert(error)
    })
  },
  methods: {
    openList (item) {
      //console.log('=============================================================')
      //console.log('item:', item)
      if (item.idobject === 'flowclmx') {
        this.$router.push({
          name: 'flowlist',
          query: { idobject: item.idobject, actiontype: 'mytask', actioncode: 'unhandle', stitle: item.stitle }
        })
      } else if (item.idobject === 'report') {
        this.$router.push({ name: 'reportlist', query: { idobject: item.idobject, stitle: item.stitle } })
      } else if (item.idobject === 'bizcalendar') {
        this.$router.push({ name: 'bizcalendar', query: { stitle: item.stitle } })
      } else if (item.idobject === '') {
        location.href = item.navurl
      } else if (item.idobject === 'bflx') {
        this.$router.push({ name: 'bflxlist', query: { idobject: item.idobject, stitle: item.stitle } })
      } else if (item.idobject === 'jhgl') {
        this.$router.push({ name: 'jhgllist', query: { idobject: item.idobject, stitle: item.stitle } })
      } else if (item.idobject === 'account') {
        this.$router.push({ name: 'accountlist', query: { idobject: item.idobject, stitle: item.stitle } })
      } else {
        this.$router.push({
          name: 'list',
          query: { idobject: item.idobject, idtemplate: item.idtemplate, stitle: item.stitle }
        })
      }
    },
    menuChange (option) {
      if (option === 'flowlist') {
        this.$router.push({
          name: 'flowlist',
          query: { idobject: 'flowclmx', actiontype: 'mytask', actioncode: 'unhandle', stitle: 'flowclmx' }
        })
      } else if (option === 'report') {
        this.$router.push({ name: 'reportlist', query: { idobject: 'report', stitle: 'report' } })
      } else if (option === 'main') {
        this.$router.push({ name: 'main' })
      } else if (option === 'homepage') {
        this.$router.push({ name: 'homepage' })
      } else if (option === 'mine') {
        this.$router.push({ name: 'mine' })
      }
    },
    loginout () {
      //console.log('logtype:', this.logintype)
      this.axios({
        method: 'post',
        url: '/api/login.loginout.do',
        data: {}
      }).then(res => {
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {
          this.$router.push({ name: 'home' })
        }
      }).catch(res => {
        this.reserror(res)
      })
    },
    changePwd () {
      this.$router.push({ name: 'changpwd' })
    },
    openUserPopup () {
      this.usershow = true
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.maintop {
  width: 100%;
  height: 20vh;
  background: linear-gradient(to bottom, #0072FB 0%, #1BA0DA 100%);
}

.menutitle {
  padding: 10px;
  font-size: 14px;
}

#app {
  padding-bottom: 8vh;
}

.main {
  padding: 2px 0px 5px 0px;
  box-sizing: border-box;
  background-color: whitesmoke;
}

.submain {
  margin: 10px 10px 10px 10px;
  background: white;
  border-radius: 10px;
  border: 1px solid white;
  padding: 10px;
  padding-bottom: 0px;
}
</style>
